package com.jeevan.tdt4260;



import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;


public class TDT4240Activity extends Activity {
	
	
	static DrawView m;
	
	
    public static void ReceiveCord (String inntekst) {
    	Point point = new Point();
    	JSONObject minJson = null;
    	try {
			minJson = new JSONObject (inntekst);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	try {
			point.x = minJson.getLong("x");
			point.y = minJson.getLong("y");
			point.state= minJson.getString("type");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	
		    m.points.add(point);
		
      //  m.points.add(point);
        m.postInvalidate();


    	 }
	
    
	static IOCallback callback = new IOCallback() {
			
			@Override
			public void onMessage(JSONObject json, IOAcknowledge ack) {
				
			 

			}
		@Override
			public void onMessage(String data, IOAcknowledge ack) {
		
			
		
			}
			
			@Override
			public void onError(SocketIOException socketIOException) {
				System.out.println("Error!!!!!!!");
				socketIOException.printStackTrace();
				
			}
			
			@Override
			public void onDisconnect() {
				
			
				
			} 
			
			@Override
			public void onConnect() {
			
				
			}
			 
			@Override
			public void on(String event, IOAcknowledge ack, Object... args) {
				
				if (event.equals("draw")){
					 
					
					for (Object arg : args)
				
					ReceiveCord(arg.toString());
				
				}
				
					
				}
			};
	
			
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	//we add the Drawingboard to the screenview.
        m = new DrawView(this);
   	 	super.onCreate(savedInstanceState);
        setContentView(m);
        
        //we establish a websocket connection to our server
        try {
        	DrawView.socket = new SocketIO();
        	DrawView.socket.connect("http://173.246.41.243:80", callback);
        	DrawView.socket.emit("adduser", "Jekyll");
        	DrawView.socket.emit("joinroom", "room1");
        	DrawView.socket.emit("sendchat", "katt");
        	
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}